<template>
  <view class="container">
    <view class="title-container">2025 Beijing SMIC School Foreign Teachers' Reservation Platform</view>

    <view class="tip">
      <view>
        <h4>Health Survey Questionnaire</h4>
        <view>
          Thank you for taking the time to complete this questionnaire. Your responses will help us better understand
          your health status and needs, and all information provided will be kept strictly confidential. Please answer
          each question as honestly as possible.
        </view>
      </view>
    </view>

    <!--    基本信息-->
    <view class="blank"></view>
    <view class="part-title"></view>

    <view class="f-flex-bet item">
      <view class="item-title">1、Your name:</view>
      <input class="part2-input" focus v-model="username" placeholder="Please enter"/>
    </view>
    <view class="blank"></view>

    <view class="f-flex-bet item">
      <text class="item-title">2、Your gender:</text>
      <uni-data-select class="name-select" v-model="gender" :localdata="genderList"
                       placeholder="Please choose"></uni-data-select>
    </view>
    <!--    条件选项-->
    <view class="blank" v-if="gender!=='Male'"></view>
    <view class="f-flex-bet item" v-if="gender!=='Male'">
      <text class="item-title">3、Female examination items</text>
      <uni-data-select class="name-select" v-model="uniToWomenVal" :localdata="uniToWomenList"
                       placeholder="Please choose"></uni-data-select>
    </view>
    <view class="blank"></view>

    <view class="f-flex-bet item">
      <text class="item-title">4、Type of ID:</text>
      <uni-data-select class="name-select" v-model="typeVal" :localdata="idTypeList"
                       placeholder="Please choose"></uni-data-select>
    </view>

    <view class="blank"></view>
    <view class="f-flex-bet item">
      <view class="item-title">5、ID number:</view>
      <input class="part2-input" focus v-model="idNumber" placeholder="Please enter"/>
    </view>

    <view class="blank"></view>
    <view class="uni-form-item uni-column">
      <view class="item-title">6、Age:</view>
      <input class="part2-input" type="number" v-model="age" maxlength="3" max="100" placeholder="Please enter"/>
    </view>
    <!--    条件选项-->
    <view class="blank" v-if="age>=40"></view>
    <view class="f-flex-bet item" v-if="age>=40">
      <text class="item-title">7、Examination items for people over 40 years old</text>
      <uni-data-select class="name-select" v-model="gt40Val" :localdata="gt40List"
                       placeholder="Please choose"></uni-data-select>
    </view>
    <view class="blank"></view>
    <view class="uni-form-item uni-column">
      <view class="item-title">8、Phone number:</view>
      <input class="part2-input" v-model="phone" placeholder="Please enter"/>
    </view>

    <view class="blank"></view>
    <view class="f-flex-bet item">
      <text class="item-title">9、Do you need an English-speaking companion for the consultation?</text>
      <uni-data-select class="name-select" v-model="enSpeakingVal" :localdata="enSpeakingList" @change="change"
                       placeholder="Please choose"></uni-data-select>
    </view>

    <view class="blank"></view>
    <view class="f-flex-bet item">
      <text class="item-title">10、Please make an appointment for the physical examination time:</text>
      <uni-data-select class="name-select" v-model="appointmentVal" :localdata="appointmentList"
                       placeholder="Please choose" @change="checkTotal"></uni-data-select>
    </view>

    <view class="blank"></view>
    <view class="f-flex-bet item">
      <text class="item-title">11、Please select the medical examination items(CT/DR).</text>
      <uni-data-select class="name-select" v-model="CTDRVal" :localdata="CTDRlIST"
                       placeholder="Please choose"></uni-data-select>
    </view>

    <!--問卷部分-->
    <QuestionnaireList ref="questionnaire" :list='questions' @answer="answerFn"/>

    <view class="blank"></view>
    <view class="btn-submit" @click="submitForm">Submit</view>

    <!--    结束-->
  </view>
</template>

<script>
import {
  qaList
} from "./data.js"
import {
  id_card_types,
  gender_list,
  uni_to_women,
  gt40_list,
  english_speaking,
  appoList1,
  appoList2,
  CTDR
} from './const.js'
import {request} from "@/utils/requestV2";
import QuestionnaireList from "@/components/questionnaire/QuestionnaireList.vue"

export default {
  data() {
    return {
      loading: false,
      questions: [],
      answerList: [],
      questionAnswerList: [],
      age: '',
      username: '',
      idTypeList: id_card_types,
      typeVal: '',
      idNumber: '',
      genderList: gender_list,
      gender: 'Male',
      phone: '',
      uniToWomenList: uni_to_women,
      gt40List: gt40_list,
      gt40Val: '',
      uniToWomenVal: '',
      enSpeakingList: english_speaking,
      enSpeakingVal: 'No',
      appointmentList: appoList2,
      appointmentVal: '',
      CTDRlIST: CTDR,
      CTDRVal: ''
    }
  },
  components: {
    QuestionnaireList
  },
  onLoad() {
    console.log('==========qaList======>', qaList)
    this.questions = qaList
  },
  methods: {
    //检测当日是否已经预约满了
    async checkTotal(date) {
      this.loading = true
      let res = await request("/biz/bizPhysicalExamination/getTotal", {date, needTranslation: this.enSpeakingVal})
      this.loading = false
      console.log("=========res========>", res)

      if (res.code !== 200) {
        uni.showToast({
          title: res.msg,
          icon: 'none',
          duration: 3000
        })
      }
    },

    change(e) {
      console.log('=========e=======>', e)
      if (e === 'No') {
        this.appointmentList = appoList2
      } else {
        this.appointmentList = appoList1
      }
    },

    answerFn(item) {
      //方案2收集答案
      let qList = this.answerList
      let index = qList.findIndex(obj => obj.questionNumber === item.questionNumber)
      index === -1 ? qList.push(item) : qList[index] = item
      this.answerList = qList
      console.log("this.answerList", this.answerList)
    },

    bindPickerChange(e) {
      this.gender = e.detail.value
      console.log("=======bindPickerChange===this.gender=======>", this.gender)
    },

    //
    async submitForm() {

      if (this.loading) {
        uni.showToast({
          icon: "none",
          title: "Please do not submit again."
        })
        return
      }

      if (!this.username) {
        uni.showToast({
          icon: "none",
          title: "Name is a required field."
        })
        return
      }

      if (!this.gender) {
        uni.showToast({
          icon: "none",
          title: "Gender is a required field."
        })
        return
      }

      if (this.gender === "Female") {
        console.log('==========this.gender======>', this.gender, this.uniToWomenVal)
        if (!this.uniToWomenVal) {
          uni.showToast({
            icon: "none",
            title: "The special health check-up items for women are mandatory."
          })
          return
        }
      }


      if (!this.typeVal) {
        uni.showToast({
          icon: "none",
          title: "Type of ID is a required field."
        })
        return
      }


      if (!this.idNumber) {
        uni.showToast({
          icon: "none",
          title: "ID number is a required field."
        })
        return
      }

      if (!this.age) {
        uni.showToast({
          icon: "none",
          title: "Age is a required field."
        })
        return
      }

      if (this.age >= 40) {
        if (!this.gt40Val) {
          uni.showToast({
            icon: "none",
            title: "Health check items are mandatory for people aged 40 and above."
          })
          return
        }
      }

      const phoneRegex = /^1\d{10}$/
      if (!phoneRegex.test(this.phone)) {
        uni.showToast({
          icon: "none",
          title: "The phone number is incorrect."
        })
        return
      }

      if (!this.appointmentVal) {
        uni.showToast({
          icon: "none",
          title: "The appointment time is a required field."
        })
        return
      }

      if (!this.CTDRVal) {
        uni.showToast({
          icon: "none",
          title: "The CT/DR is a required field."
        })
        return
      }

      this.processQues('null') && this.doSubmit();
    },

    /**
     * 处理数据
     * 2024.07.26
     */
    processQues(dataList) {
      let list = []
      if (dataList === 'null') {
        list = this.questions
      } else {
        list = dataList
      }

      let questionAnswerList = this.answerList.map(item => {
        return {
          questionId: item.questionNumber,
          optionValue: item.fValue
        }
      })
      this.questionAnswerList = questionAnswerList

      let verifyPass = true
      for (let item of list) {
        if (item.subQuestions && item.subQuestions.length > 0) {
          this.processQues(item.subQuestions)
        } else {
          let quesItem = questionAnswerList.find(ele => ele.questionId === item.questionNumber)
          console.log("quesItem", quesItem);
          if (!quesItem) {
            uni.showToast({
              title: `${item.questionNumber}、${item.questionName} is a required field.`,
              icon: "none"
            })
            verifyPass = false
            break;
          }

          if (item.type === 'text_int') {
            if (!/^\d+$/.test(quesItem.optionValue)) {
              uni.showToast({
                title: `${item.questionName}只能是数字`,
                icon: "none"
              })
              verifyPass = false
              break;
            }
          }

        }
      }

      //提交数据
      console.log('========验证结果========>', verifyPass)
      return verifyPass
    },

    async doSubmit() {

      let payload = {
        username: this.username,
        gender: this.gender,
        requiredForFemale: this.gender === "Female" ? this.uniToWomenVal : '',
        idType: this.typeVal,
        idNumber: this.idNumber,
        age: this.age,
        phoneNumber: this.phone,
        over40Options: Number(this.age) >= 40 ? this.gt40Val : '',
        needTranslation: this.enSpeakingVal,
        ctdr: this.CTDRVal,
        appointmentTime: this.appointmentVal,
        appointmentData: JSON.stringify(this.answerList)
      }

      //submit
      console.log("========payload=========>", payload)

      //开始提交
      this.loading = true
      let res = await request("/biz/bizPhysicalExamination/add", payload, "POST")
      this.loading = false
      console.log("=========res========>", res)

      if (res.code === 200) {
        uni.showToast({
          title: "Appointment successful!"
        })
        setTimeout(function () {
          uni.navigateTo({
            url: "/pages/enqa/result?id=" + res.msg
          })
        }, 1500)
      } else {
        uni.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    }

//
  }
}
</script>

<style lang="scss" scoped>
.container {
  font-size: 14px;
  padding: 30px 15px;
}

.title-container {
  font-size: 14px;
  color: #333;
  font-weight: bold;
  text-align: center;
  margin-bottom: 15px;
}

.item-title {
  padding: 5px 0;
  color: #666666;
  font-size: 14px;
}

.tip {
  background-color: #42b983;
  color: #ffffff;
  padding: 15px;
  line-height: 30px;
}

.title {
  font-size: 14px;
  color: #333;
  font-weight: bold;
}

.list {
  padding: 10px 0;
  border-bottom: 1px solid #999;
  line-height: 30px;
}

.flex-b {
  display: flex;
  align-items: center;
}

.ans2 {
  font-size: 12px;
  padding-left: 20px;
}

.score {
  width: 25px;
  height: 25px;
  border: 1px solid #999;
  text-align: center;
}

.scoreB {
  width: 25px;
  height: 25px;
  border: 1px solid #999;
  background-color: #f0f0f0;
  text-align: center;
}

.blank {
  height: 15px;
}

.part-title {
  font-size: 14px;
}

.part2-input-title {
  padding: 10px 0;
}

.part2-input {
  border: 1px solid #dddddd;
  padding: 5px 10px;
  border-radius: 3px;
}

.uni-input {
  padding: 0 10px;
}

.uni-list-cell-db {
  border: 1px solid #999;
  padding: 5px 0;
}

.btn-submit {
  padding: 15px 0;
  background-color: #42b983;
  text-align: center;
  color: #ffffff;
}

.line {
  flex: 1;
  height: 1px;
  border-bottom: 1px dashed #999;
  margin: 0 20px;
}

.line-number {
  justify-content: space-between;
}

</style>